/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sample.DAO;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import sample.entity.Account;
import sample.util.*;

/**
 *
 * @author kmq
 */
public class AccountDAO {
    private Session session;
    
    /**
     * Constructor
     */
    public AccountDAO(){
        SessionFactory factory = HibernateUtil.getSessionFactory();
        this.session = factory.getCurrentSession();
    }
    
    /**
     * Insert
     */
    public void add(Account acc){
        try{
           session.getTransaction().begin();
           session.save(acc);
           session.flush();
           session.getTransaction().commit();
        }
        catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.getStackTrace();
        }
    }
    
    /**
     * Delete
     */
    public void delete(int id){
        try{
            session.getTransaction().begin();
            session.delete(session.get(Account.class, id));
            session.flush();
            session.getTransaction().commit();
            
        }
        catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.getStackTrace();
            e.getMessage();
        }
    }
    
    /**
     * Update
     */
    public void update(Account newAcc, int id){
        try{
            session.getTransaction().begin();
            Account acc = (Account) session.get(Account.class, id);
            acc.setLastname(newAcc.getLastname());
            acc.setPassword(newAcc.getPassword());
            acc.setUsername(newAcc.getUsername());
            acc.setRoles(newAcc.isRoles());
            session.update(acc);
            session.flush();
            session.getTransaction().commit();
        }
        catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.getStackTrace();
        }
    }
    
    /**
     * check Login
     */
    public Account checkLogin(String username, String password){
        try{
            session.getTransaction().begin();
            String sql = "from Account where username=? and password=?";
            Query query = session.createQuery(sql);
            query.setString(0, username);
            query.setString(1, password);
            
            Account result = (Account) query.uniqueResult();
            session.flush();
            session.getTransaction().commit();
            return result;
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.getStackTrace();
        }
        return null;
    }
}
